-- UIConfirm2
-- Create by chengb Nov/25/2014
-- 确认提示框界面

CONFIRM_TYPE_OK          = 1   -- 只有确定按钮
CONFIRM_TYPE_OK_CANCEL   = 2   -- 确定和取消按钮
CONFIRM_TYPE_OK_NOBACK   = 3   -- 只有确定按钮，且没有返回按钮

CONFIRM_BG_TYPE_PET       = 1
CONFIRM_BG_TYPE_WORKSHOP  = 2
CONFIRM_BG_TYPE_FOOD      = 3

-- 每行最多的文字数量
local LINE_WORD_COUNT = 15;

--UIConfirm2继承自Layer
UIConfirm2 = class("UIConfirm2", function()
    return cc.Layer:create();
end)

----------------------------------------------------
-- @param confirmType  类型 CONFIRM_TYPE_OK 只有确认按钮， CONFIRM_TYPE_OK_CANCEL 有确认取消按钮
-- @param title        确定标题文本
-- @param msg          提示框的内容
-- @param okFunc       点击确认的处理函数
-- @param cancelFunc   点击取消的处理函数
-- @param okText       确定按钮文本
-- @param cancelText   取消按钮文本
-- @param extraPara    附加参数
function UIConfirm2.create(confirmType, title, msg, okFunc, cancelFunc, okText, cancelText, extraPara)
    return UIConfirm2.new(confirmType, title, msg, okFunc, cancelFunc, okText, cancelText, extraPara);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIConfirm2:ctor(confirmType, title, msg, okFunc, cancelFunc, okText, cancelText, extraPara)
    self:setName("UIConfirm2");
    -- 初始化
    local node = cc.CSLoader:createNode("layout/dialog/Confirm2.csb");
    self:addChild(node);
    self.node = node;
    self.type = confirmType;

    local CT = findChildByName(node, "CT");

    self.title = title;
    self.msg = msg;
    self.okFunc = okFunc;
    self.cancelFunc = cancelFunc;
    self.okText = okText;
    self.cancelText = cancelText;
    extraPara = extraPara or {};
    self.extraPara = extraPara;

    self.backBtn = findChildByName(node, "BT/btn_back");

    if self.type == CONFIRM_TYPE_OK then
        self.okBtn = findChildByName(CT, "ok/btn_ok");
        self.okBtn:setVisible(true);
    elseif self.type == CONFIRM_TYPE_OK_CANCEL then
        self.okBtn = findChildByName(CT, "ok_cancel/btn_ok");
        self.okBtn:setVisible(true);
        self.cancelBtn = findChildByName(CT, "ok_cancel/btn_cancel");
        self.cancelBtn:setVisible(true);
    elseif self.type  == CONFIRM_TYPE_OK_NOBACK then
        self.okBtn = findChildByName(CT, "ok/btn_ok");
        self.okBtn:setVisible(true);
        self.backBtn:setVisible(false);
    end

    if extraPara["hideBackBtn"] == true then
        self:hideBackBtn();
    end

    -- 重绘
    self:redraw();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 调整高度
    self:adjustHeight();

    -- 适配
    resize(node);
end

-- 重绘
function UIConfirm2:redraw()
    local node = self.node;
    local CT = findChildByName(node, "CT");
    local extraPara = self.extraPara;
    local title = self.title;
    local msg = self.msg;

    -- 设置标题
    self.titleLabel = CT:getChildByName("title");
    if extraPara["titleIcon"] then
        self.titleLabel:setVisible(false);
        self.titleLabel = CT:getChildByName("title2");
        self.titleLabel:setVisible(true);
        local titleIcon = findChildByName(self.titleLabel, "icon");
        titleIcon:loadTexture(extraPara["titleIcon"]);
        self.titleLabel:setString(title);
        self.titleLabel:setFontSize(TextStyleM.TEXT_SIZE_MIDDLE);
        self.titleLabel:setTextColor(TextStyleM.TEXT_COLOR_BLUE);
        self.titleLabel:setPositionX(0 - (getRealContentSize(self.titleLabel).width - 60) / 2);
    else
        TextStyleM.setTitleStyle(self.titleLabel);
        self.titleLabel:setString(title);
    end

    -- 设置确定按钮文本
    local okBtn = self.okBtn;
    local okText = self.okText;
    TextStyleM.setTextStyle(okBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    if not okText then
        okBtn:setTitleText(getLocStr("confirm"));
    else
        okBtn:setTitleText(okText);
    end

    -- 置灰不允许点击
    if extraPara.okBtnEnable ~= nil then
        okBtn:setTouchEnabled(extraPara.okBtnEnable);
        okBtn:setBright(extraPara.okBtnEnable);
    end

    -- 设置内容
    local contentLabel = CT:getChildByName("content");
    TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    contentLabel:getVirtualRenderer():setLineHeight(TextStyleM.TEXT_SIZE_SMALL + 5);

    -- 设置左对齐
    if extraPara["alignment_left"] then
        contentLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT);
    end

    if extraPara["lifeRecoverTime"] then
        -- 需要显示倒计时
        local lifeCost = FormulaM.invoke("CALC_BOSS_LAYER_COST_LIFE");
        local function tick()
            local leftTime = math.floor(UserM.getLifeRecoveryLeftTime());

            if ME.user.dbase:query("life", 0) >= lifeCost then
                -- 体力够了，关闭当前界面
                UIMgr.getCurrentScene():removeDialog(self);

                -- 重新开页面
                showCostLifeInDungeon();
                return;
            end

            local secs = leftTime % 60;
            local mins = math.floor(leftTime / 60);
            msg = string.format(getLocStr("boss_layer_cost_life_msg2"), lifeCost, mins, secs);
            TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            contentLabel = applyString(contentLabel, msg);

            performWithDelay(self.node, tick, 1);
        end

        tick();
    elseif extraPara["leftTimeDesc"] then
        -- 描述要求倒计时回调
        contentLabel = self:redrawDescTick(extraPara["leftTimeDesc"]);
    elseif extraPara["skyExploreTime"] then
        -- 天空探索重置倒计时
        local function tick()
            local leftTime = math.floor(SkyExploreM.getFailResetTime(extraPara["skyExploreTime"]));
            local descMsg = msg .. "\n" .. string.format(getLocStr("left_time_to_reset"), remainingTimeDesc(leftTime));
            TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            contentLabel = applyString(contentLabel, descMsg);

            if leftTime <= 0 then
                -- 倒计时结束了，直接关闭界面
                UIMgr.getCurrentScene():removeDialog(self);
                return;
            end
            performWithDelay(self.node, tick, 1);
        end
        tick();
    else
        contentLabel = applyString(contentLabel, msg, nil, nil, nil, extraPara["line_word_count"] or LINE_WORD_COUNT);
    end
    self.contentLabel = contentLabel;

    -- 月卡升级时按钮上显示消耗
    if extraPara.form_name ~= nil and extraPara.form_name == "UIMonthlyCard" then
        -- 显示所有的消耗图标
        local btnText = findChildByName(CT, "ok/btn_ok/btn_text");
        TextStyleM.setTextStyle(btnText, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnText:setString(getLocStr("btn_text_upgrade2"));
        btnText:setVisible(true);

        local btnImg = findChildByName(CT, "ok/btn_ok/btn_img");
        btnImg:loadTexture(getSmallAttribIconPath(FieldsM.query("gem", "icon")));
        btnImg:setVisible(true);

        local gemNumLabel = findChildByName(CT, "ok/btn_ok/num_label");
        gemNumLabel:setVisible(true);

        local curLevel = SuperiorM.getSuperiorLevel();
        local cost = SuperiorM.query(curLevel, "upgrade_cost") or {};
        TextStyleM.setTextStyle(gemNumLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        gemNumLabel:setString(tostring(cost.gem));
    end
end

-- 注册点击事件
function UIConfirm2:registerTouchEvent()
    local extraPara = self.extraPara;
    local btnBack = self.backBtn;
    local okFunc = self.okFunc;
    local cancelFunc = self.cancelFunc;
    local okText = self.okText;
    local cancelText = self.cancelText;

    -- 注册确认按钮点击事件
    local okBtn = self.okBtn;
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_select");
            UIMgr.getCurrentScene():removeDialog(self);
            if type(okFunc) == 'function' then
                okFunc();
                return true;
            end
            return false;
        end
    end
    okBtn:addTouchEventListener(onOkClick);

    -- 注册取消按钮点击事件
    local cancelBtn = self.cancelBtn;
    if cancelBtn ~= nil then
        local function onCancelClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_return");
                UIMgr.getCurrentScene():removeDialog(self);
                if type(cancelFunc) == 'function' then
                    cancelFunc();
                end
            end
        end
        AddBackEventHandler(self, cancelBtn, onCancelClick);
        TextStyleM.setTextStyle(cancelBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        cancelBtn:setTitleText(getLocStr("btn_text_cancel"));

        self.onCancelClick = onCancelClick;

        -- 设置取消按钮文本
        if not cancelText then
            cancelBtn:setTitleText(getLocStr("btn_text_cancel"));
        else
            cancelBtn:setTitleText(cancelText);

            -- 如果自定义取消按钮文本，则按钮的样式和确定按钮一致
            cancelBtn:loadTextures("images/ui/button/btn_large_yellow1.png", "images/ui/button/btn_large_yellow2.png");
        end

        -- 如果有传入按钮的颜色，则设置按钮样式
        local okColor     = extraPara.okColor;
        local cancelColor = extraPara.cancelColor;
        if okColor ~= nil then
            okBtn:loadTextures(string.format("images/ui/button/btn_large_%s1.png", okColor), string.format("images/ui/button/btn_large_%s2.png", okColor));
        end

        if cancelColor ~= nil then
            cancelBtn:loadTextures(string.format("images/ui/button/btn_large_%s1.png", cancelColor), string.format("images/ui/button/btn_large_%s2.png", cancelColor));
        end
    end

    -- 注册返回按钮点击事件
    if type(extraPara.backText) == "string" then
        btnBack:setTitleText(getLocStr(extraPara.backText));
    else
        btnBack:setTitleText(getLocStr("btn_text_back"));
    end

    -- 设置返回按钮的底图风格
    if extraPara.backStyle == "yellow" then
        btnBack:loadTextures("images/ui/button/btn_normal_yellow1.png", "images/ui/button/btn_normal_yellow2.png");
    end

    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeDialog(self);

            if type(extraPara.backFunc) == "function" then
                -- 如果传入了返回回调，调用之
                extraPara.backFunc();
            end
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
end

-- 描述有时间回调
function UIConfirm2:redrawDescTick(timeType)
    local CT = findChildByName(self.node, "CT");
    local contentLabel = CT:getChildByName("content");
    if timeType[1] == "relic" or timeType[1] == "boss" then
        -- 掠夺的
        local function tick()
            local finalTime = timeType[2];
            local leftTime = finalTime - TimeM.getServerTime();
            local desc = string.format(getLocStr("last_rob_fail_tip"), remainingTimeDesc(leftTime));
            TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            contentLabel = applyString(contentLabel, desc);
            if leftTime <= 0 then
                -- 倒计时结束了，直接关闭界面
                UIMgr.getCurrentScene():removeDialog(self);
                return;
            end
            performWithDelay(self.node, tick, 1);
        end
        tick();
    elseif timeType[1] == "revenge" then
        -- 复仇的
        local function tick()
            local finalTime = timeType[2];
            local leftTime = finalTime - TimeM.getServerTime();
            local desc = string.format(getLocStr("last_revenge_fail_tip"), remainingTimeDesc(leftTime));
            TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            contentLabel = applyString(contentLabel, desc);
            if leftTime <= 0 then
                -- 倒计时结束了，直接关闭界面
                UIMgr.getCurrentScene():removeDialog(self);
                return;
            end
            performWithDelay(self.node, tick, 1);
        end
        tick();
    elseif timeType[1] == "maintain" then
        -- 维护公告倒计时

        local leftTime = timeType[3];
        local function tick()
            local content = timeType[2];
            local desc = string.gsub(content, "{left_time}", remainingTimeDesc2(leftTime));
            desc = string.gsub(desc, "%%s", remainingTimeDesc2(leftTime));

            TextStyleM.setTextStyle(contentLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            contentLabel = applyString(contentLabel, desc);
            -- contentLabel:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_LEFT);
            if leftTime <= 0 then
                -- 倒计时结束了，直接关闭界面
                -- UIMgr.getCurrentScene():removeDialog(self);
                return;
            end

            leftTime = leftTime - 1;
            performWithDelay(self.node, tick, 1);
        end
        tick();
    end
    return contentLabel;
end

-- 隐藏返回按钮
function UIConfirm2:hideBackBtn()
    local btnBack = findChildByName(self.node, "BT/btn_back");
    btnBack:setVisible(false);
end

-- 设置底图类型
function UIConfirm2:setBgType(bgType)
    local bg1 = findChildByName(self.node, "CT/bg1")

    if bgType == CONFIRM_BG_TYPE_PET then
        bg1:loadTexture("images/ui/common_bg/pet.png");
    elseif bgType == CONFIRM_BG_TYPE_WORKSHOP then
        bg1:loadTexture("images/ui/common_bg/pet.png");

        local bg2 = findChildByName(self.node, "CT/bg2");
        bg2:setVisible(false);
    elseif bgType == CONFIRM_BG_TYPE_FOOD then
        bg1:loadTexture("images/ui/common_bg/food.png");
    end
end

-- 调整高度
function UIConfirm2:adjustHeight()
    -- 老的高度和缩放
    local bgFrame = findChildByName(self.node, "CT/bg_frame");
    local oldHeight = 272 * bgFrame:getScaleY();
    local oldScaleY = bgFrame:getScaleY();

    local textHeight = self.contentLabel:getContentSize().height * 1.2;

    local margin = 160;
    local newHeight = textHeight + margin * 2;

    if newHeight <= oldHeight then
        return;
    end

    -- 新的Y轴缩放
    local newScaleY = newHeight * oldScaleY / oldHeight;
    bgFrame:setScaleY(newScaleY);

    local delta = (newHeight - oldHeight) / 2;

    -- 标题上移delta像素
    self.titleLabel:setPositionY(self.titleLabel:getPositionY() + delta);

    -- 底图
    local bg1 = findChildByName(self.node, "CT/bg1");
    local bg2 = findChildByName(self.node, "CT/bg2");
    bg1:setPositionY(bg1:getPositionY() + delta);
    bg2:setPositionY(bg2:getPositionY() + delta);

    -- 按钮下移delta像素
    self.okBtn:setPositionY(self.okBtn:getPositionY() - delta);
    if self.cancelBtn then
        self.cancelBtn:setPositionY(self.cancelBtn:getPositionY() - delta);
    end
end

-- 适配
resize = function(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

return UIConfirm2;
